package com.smasher.demo;

import android.os.Bundle;
import android.util.Log;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.smasher.mqtt.EasyMqttClient;
import com.smasher.mqtt.config.EasyMqttOptions;
import com.smasher.mqtt.receivers.TopicMessageReceiver;

public class MainActivity extends AppCompatActivity {

    public static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        findViewById(R.id.start).setOnClickListener(v -> initMqtt());
        findViewById(R.id.stop).setOnClickListener(v -> disconnect());
        findViewById(R.id.publish).setOnClickListener(v -> publish());
    }

    private void initMqtt() {
        EasyMqttOptions options = EasyMqttOptions.getDefaultOptions();
        options.setAddress("tcp://192.168.1.137:1883");
        options.setDefaultTopic("iot/nxfhc/device/service");
        options.setDefaultTopicQos(1);
        options.setDefaultTopicRetained(true);
        options.setUserName("admin");
        options.setPassWord("Abc12345");
        options.setClientId("Android");
        options.setConnectTimeout(10);
        options.setKeepAliveInterval(20);

        EasyMqttClient.getInstance().createConnection(options, this);
        EasyMqttClient.getInstance().addMessageReceive(new TopicMessageReceiver("iot/nxfhc/device/service") {
            @Override
            public void onMessageReceived(String msg) {
                Log.d(TAG, "onMessageReceived: " + msg);
            }
        });
    }

    private void publish() {
        EasyMqttClient.getInstance().publish("iot/nxfhc/device/service", "hello world", 1, true);
    }

    private void disconnect() {
        EasyMqttClient.getInstance().disconnect();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EasyMqttClient.getInstance().destroy();
    }
}